package com.lyh.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lyh.pojo.Bill;
import com.lyh.pojo.Provider;
import com.lyh.pojo.User;
import com.lyh.service.bill.BillService;
import com.lyh.service.provider.ProviderService;
import com.lyh.utils.Constants;
import com.lyh.utils.PageSupport;
import com.mysql.cj.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Controller
@RequestMapping("/bill")
public class BillController {

    public BillService billService;

    @Autowired
    public void setBillService(BillService billService) {
        this.billService = billService;
    }

    @RequestMapping("/billList")
    public String billList(Model model,
                            @RequestParam(name = "queryProductName", required = false)String productName,
                            @RequestParam(name = "queryProviderId",required = false)String providerId,
                            @RequestParam(name = "queryIsPayment",required = false)String isPayment,
                            @RequestParam(name = "pageIndex",required = false)String pageNo) {

        HashMap<String, Object> map = new HashMap<>();
        int currentPageNo = 1;
        int isPaymentTemp = 0;
        int providerIdTemp = 0;

        if (StringUtils.isNullOrEmpty(productName)) {
            map.put("productName",null);
        } else {
            map.put("productName",productName.trim());
        }

        if (StringUtils.isNullOrEmpty(providerId)) {
            map.put("providerId",providerIdTemp);
        } else {
            providerIdTemp = Integer.valueOf(providerId);
            map.put("providerId",providerIdTemp);
        }

        if (StringUtils.isNullOrEmpty(isPayment)) {
            map.put("isPayment",isPaymentTemp);
        } else {
            isPaymentTemp = Integer.valueOf(isPayment);
            map.put("isPayment",isPaymentTemp);
        }

        if (StringUtils.isNullOrEmpty(pageNo)) {
            map.put("currentPageNo",currentPageNo);
        } else {
            currentPageNo = Integer.valueOf(pageNo.trim());
        }

        //BillService billService = Constants.context.getBean("billService", BillService.class);
        ProviderService providerService = Constants.context.getBean("providerService", ProviderService.class);

        int billCount = billService.countBills(map);

        // 计算页数
        PageSupport pageSupport = new PageSupport();
        // 设置每页显示数量
        pageSupport.setPageSize(6);
        // 设置需要显示得总数，并计算总页数
        pageSupport.setTotalCount(billCount);
        // 获取总页数
        int totalPageCount = pageSupport.getTotalPageCount();
        // 设置当前页面
        pageSupport.setCurrentPageNo(currentPageNo);

        //控制首页和尾页的正常值
        if(currentPageNo<1){
            currentPageNo=1;
        }else if(currentPageNo>totalPageCount){
            currentPageNo=totalPageCount;
        }

        // 计算需要显示的数据的开始下标
        map.put("currentPageNo",(currentPageNo-1)*6);
        // 设置从该下标起显示个数
        map.put("PageSize",6);


        List<Provider> providerList = providerService.getProviderNameList();
        List<Bill> billList = billService.getBillList(map);

        model.addAttribute("providerList",providerList);
        model.addAttribute("billList",billList);

        model.addAttribute("queryProductName",productName);
        model.addAttribute("queryProviderId",providerIdTemp);
        model.addAttribute("queryIsPayment",isPaymentTemp);
        model.addAttribute("totalPageCount",totalPageCount);
        model.addAttribute("totalCount",billCount);
        model.addAttribute("currentPageNo",currentPageNo);

        return "billlist";
    }

    @RequestMapping("/toBillView/{billId}")
    public String toBillView(@PathVariable(name = "billId")String billId, Model model) {

        //BillService billService = Constants.context.getBean("billService", BillService.class);

        int billIdTemp = Integer.valueOf(billId);
        Bill bill = billService.getBillById(billIdTemp);

        model.addAttribute("bill",bill);
        return "billview";
    }

    @RequestMapping("/toModifyBill/{billId}")
    public String toModifyBill(@PathVariable(name = "billId")String billId, Model model) {

        //BillService billService = Constants.context.getBean("billService", BillService.class);

        int billIdTemp = Integer.valueOf(billId);
        Bill bill = billService.getBillById(billIdTemp);

        model.addAttribute("bill",bill);
        return "billmodify";
    }

    @RequestMapping("/modifyBill")
    @ResponseBody
    public void modifyBill(HttpServletRequest request, HttpServletResponse response) {

        String billCode = request.getParameter("billCode");
        String productName = request.getParameter("productName");
        String productUnit = request.getParameter("productUnit");
        BigDecimal productCount = BigDecimal.valueOf(Double.parseDouble(request.getParameter("productCount")));
        BigDecimal totalPrice = BigDecimal.valueOf(Double.parseDouble(request.getParameter("totalPrice")));
        int isPayment = Integer.valueOf(request.getParameter("isPayment"));
        int providerId = Integer.valueOf(request.getParameter("providerId"));

        User user = (User) request.getSession().getAttribute(Constants.USER_SESSION);
        int modifyBy = user.getId();

        Bill bill = new Bill(billCode, productName, productUnit, productCount, totalPrice, isPayment, modifyBy, new Date(), providerId);

        //BillService billService = Constants.context.getBean("billService", BillService.class);
        int i = billService.modifyBill(bill);

        if (i>0) {
            System.out.println("修改成功");
            try {
                request.getRequestDispatcher("billList").forward(request, response);
            } catch (ServletException | IOException e) {
                e.printStackTrace();
            }
        } else {
            request.setAttribute("msg","修改订单失败");
        }
    }

    @RequestMapping("/toBillAdd")
    public String toBillAdd() {

        return "billadd";
    }

    @RequestMapping("/addBill")
    @ResponseBody
    public void addBill(HttpServletRequest request, HttpServletResponse response) {
        String billCode = request.getParameter("billCode");
        String productName = request.getParameter("productName");
        String productUnit = request.getParameter("productUnit");
        BigDecimal productCount = BigDecimal.valueOf(Double.parseDouble(request.getParameter("productCount")));
        BigDecimal totalPrice = BigDecimal.valueOf(Double.parseDouble(request.getParameter("totalPrice")));
        int isPayment = Integer.valueOf(request.getParameter("isPayment"));
        int providerId = Integer.valueOf(request.getParameter("providerId"));

        User user = (User) request.getSession().getAttribute(Constants.USER_SESSION);
        int modifyBy = user.getId();

        Bill bill = new Bill(billCode, productName, productUnit, productCount, totalPrice, isPayment, modifyBy, new Date(), providerId);
        bill.setCreatedBy(modifyBy);
        bill.setCreationDate(new Date());

        //BillService billService = Constants.context.getBean("billService", BillService.class);
        int i = billService.addBill(bill);

        if (i>0) {
            System.out.println("添加成功");
            try {
                request.getRequestDispatcher("billList").forward(request, response);
            } catch (ServletException | IOException e) {
                e.printStackTrace();
            }
        } else {
            request.setAttribute("msg","添加订单失败");
        }
    }

    @RequestMapping("/deleteBill/{id}")
    @ResponseBody
    public String deleteBill(@PathVariable("id") String id) throws JsonProcessingException {
        //BillService billService = Constants.context.getBean("billService", BillService.class);
        HashMap<String, String> map = new HashMap<>();
        int i = billService.deleteBill(Integer.valueOf(id));
        if (i>0) {
            map.put("delResult","true");
        } else {
            map.put("delResult","false");
        }
        ObjectMapper objectMapper = new ObjectMapper();
        String s = objectMapper.writeValueAsString(map);
        return s;
    }
}
